import argparse
import sqlite3


def add_column_to_table(
    database_path, table_name, column_name, column_type, default_value=None
):
    """
    向 SQLite 数据库中的表添加一列。

    :param database_path: SQLite 数据库文件路径
    :param table_name: 要修改的表名
    :param column_name: 要添加的列名
    :param column_type: 列的数据类型
    :param default_value: 列的默认值（可选）
    """
    conn = None
    try:
        # 连接到 SQLite 数据库
        conn = sqlite3.connect(database_path)
        cursor = conn.cursor()

        # 检查列是否已存在
        cursor.execute(f"PRAGMA table_info({table_name})")
        columns = cursor.fetchall()
        for col in columns:
            if col[1] == column_name:
                print(f"列 '{column_name}' 已存在于表 '{table_name}' 中。")
                return

        # 构建 ALTER TABLE 语句
        alter_table_sql = (
            f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}"
        )
        if default_value is not None:
            alter_table_sql += f" DEFAULT {default_value}"

        # 执行 ALTER TABLE 语句
        cursor.execute(alter_table_sql)
        conn.commit()
        print(f"成功向表 '{table_name}' 添加列 '{column_name}'。")

    except sqlite3.Error as e:
        print(f"SQLite 错误: {e}")
    finally:
        if conn:
            conn.close()


def main():
    # python scripts/insert_sqlite_columns.py --db_path ./instance/users.db --table_name snapshot --column_name dev_env_name --column_type "VARCHAR(100)"
    parser = argparse.ArgumentParser(description="Add a new column to a SQLite table.")
    parser.add_argument("--db_path", help="Path to the SQLite database file")
    parser.add_argument("--table_name", help="Name of the table to modify")
    parser.add_argument("--column_name", help="Name of the new column to add")
    parser.add_argument(
        "--column_type", help="Type of the new column (e.g., TEXT, INTEGER)"
    )
    parser.add_argument(
        "--default_value", help="Default value for the new column", default=None
    )

    args = parser.parse_args()

    add_column_to_table(
        args.db_path,
        args.table_name,
        args.column_name,
        args.column_type,
        args.default_value,
    )


if __name__ == "__main__":
    main()
